package com.shangxian.giveithome.service.impl;


import com.shangxian.giveithome.code.CommonCode;
import com.shangxian.giveithome.entity.PageableDetails;
import com.shangxian.giveithome.entity.UserDetails;
import com.shangxian.giveithome.entity.UserSimple;
import com.shangxian.giveithome.entity.community.*;
import com.shangxian.giveithome.exception.ExceptionUtils;
import com.shangxian.giveithome.mapper.*;
import com.shangxian.giveithome.service.CollectionService;
import com.shangxian.giveithome.utils.PageUtils;
import com.shangxian.giveithome.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class CollectionServiceImpl  implements CollectionService {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private CollectionsMapper collectionsMapper;

    @Autowired
    private IssueImgMapper issueImgMapper;

    @Autowired
    private AttentionMapper attentionMapper;

    @Autowired
    private IssueMapper issueMapper;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired AdoptionMapper adoptionMapper;

    @Override
    public PageableDetails findCollectionsList(Pageable pageable, HttpServletRequest request,Long id) {
        int pageNumber = pageable.getPageNumber();
        int pageSize = pageable.getPageSize();
        if (id ==null && redisUtils.getHeader(request) ==null){
            ExceptionUtils.error(CommonCode.PARAMETER_ERROR);
        }
        if (id != null) {
            int total = collectionsMapper.findCollectionCount(id);
            if (total == 0) {
                return new PageableDetails<>(pageNumber, pageSize, total, returnPages(total, pageSize), new ArrayList<>());
            }
            List<CollectionsList> collectionsList = collectionsMapper.findCollectionsList(id, pageNumber * pageSize, pageSize);
            return new PageableDetails<>(pageNumber, pageSize, total, returnPages(total, pageSize), collectionsList);
        }
            UserDetails userDetails = redisUtils.getHeader(request);
            int total1 = collectionsMapper.findCollectionCount(userDetails.getId());
            if (total1 == 0) {
                return new PageableDetails<>(pageNumber, pageSize, total1, returnPages(total1, pageSize), new ArrayList<>());
            }
            List<CollectionsList> collectionsList = collectionsMapper.findCollectionsList(userDetails.getId(), pageNumber * pageSize, pageSize);
            return new PageableDetails<>(pageNumber, pageSize, total1, returnPages(total1, pageSize), collectionsList);
    }

    @Override
    public PageableDetails findUserCollectionsListDetails(Pageable pageable, Long id) {
        int pageNumber = pageable.getPageNumber();
        int pageSize = pageable.getPageSize();
        int total  = issueMapper.findCollectionIssueCount(id);
        if (total ==0){
            return new PageableDetails<>(pageNumber,pageSize,total,returnPages(total,pageSize),new ArrayList<>());
        }
        List<IssueList> issueLists = collectionsMapper.findAttentionUserCollectionsListDetails(id, pageNumber * pageSize, pageSize);
        if (issueLists.size() !=0) {
            List<Long> ids = issueLists.stream().map(IssueList::getImgId).collect(Collectors.toList());
            List<IssueImg> issueImgs = issueImgMapper.findIssueImgByIds(ids);
            UserList userLists = attentionMapper.findAttentionCollectionUserMessage(id);
            issueLists.forEach(issueList -> {
                issueList.setName(userLists.getName());
                issueList.setPicture(userLists.getPicture());
                issueList.setImgPath("");
                for (IssueImg issueImg : issueImgs) {
                    if (issueList.getImgId() != null && issueList.getImgId().equals(issueImg.getKeyId())) {
                        issueList.setImgPath(issueImg.getPath());
                        break;
                    }
                }
            });
        }
        return new PageableDetails<>(pageNumber,pageSize,total,returnPages(total,pageSize),issueLists);
    }
    @Transactional
    @Override
    public void addCollection(Collections collections,HttpServletRequest request) {
        UserDetails userDetails = redisUtils.getHeader(request);
        if (userDetails ==null){
            ExceptionUtils.error(CommonCode.AUTH_NOT_SUCCESS);
        }
        int i = collectionsMapper.findCollectionNameByUserId(userDetails.getId(),collections.getCollectionName());
        if (i<1){
            collections.setUserId(userDetails.getId());
            int a = collectionsMapper.addCollection(collections);
            if (a<1){
                ExceptionUtils.error(CommonCode.DATA_ERRORS);
            }
        }

    }

    @Override
    public CollectionsList addAdoptCollection(Long id, HttpServletRequest request) {
            PetSimpleInformation pet = petMapper.findPetInformation(id);
            if (pet == null) {
                ExceptionUtils.error(CommonCode.DATA_ERROR);
            }
         Long collectionId = petMapper.findAdCollectionId(id);
         CollectionsList collection = collectionsMapper.findCollection(collectionId);
           UserSimple userSimple = adoptionMapper.findSUserSimpleByPetId(id);
           if (!userSimple.getId().equals(redisUtils.getHeader(request).getId())) {
            if (collectionId == null) {
                UserDetails userDetails = redisUtils.getHeader(request);
                Collections collections = new Collections();
                collections.setPetId(id);
                if (pet.getName() == null || pet.getName().equals("")) {
                    collections.setCollectionName("小可爱的领养合集");
                } else {
                    String petName = pet.getName() + "的领养合集";
                    collections.setCollectionName(petName);
                }
                collections.setUserId(userDetails.getId());
                int i = collectionsMapper.addAdoptCollection(collections);
                if (i < 1) {
                    ExceptionUtils.error(CommonCode.DATA_ERRORS);
                }
                collectionId = petMapper.findAdCollectionId(id);
                collection = collectionsMapper.findCollection(collectionId);
                collection.setState(0);
                return collection;
            }
        }
           if (collection == null){
               return  new CollectionsList();
           }
        collection.setState(1);
        return collection;
    }


    /**
     * 返回
     *
     * @param pageNumber 当前页
     * @param pageSize   每页条数
     * @param count      总条数
     * @param list       返回数据
     * @param <T>        泛型
     * @return
     */
    public <T> PageableDetails returnPageable(int pageNumber, Integer pageSize, Integer count, List<T> list) {
        return new PageableDetails<>(pageNumber, pageSize, count, list);
    }

    /**
     * 返回总页数
     *
     * @param total
     * @param pageSize
     * @return
     */
    public int returnPages(int total, int pageSize) {
        return PageUtils.returnPages(total, pageSize);
    }

}
